<?php

namespace app\api\controller\v1;


use app\api\model\v1\ActivityForm;
use app\api\model\v1\ActivityShare;
use app\api\model\v1\ActivitySign;
use app\api\model\v1\Mincode;
use app\api\model\v1\UserReadLog;
use app\api\model\v1\UserReadShareLog;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Attachment;
use think\Db;
use think\File;
use think\Image;

class Activity extends Base
{
    protected $noNeedLogin = ['list'];
    public function list()
    {
        $list = \app\api\model\v1\Activity::getList($this->reqParams);
        $this->success('活动列表', $list);
    }

    public function detail(){
        $activityId = $this->reqParams['activity_id'];
        $activity = \app\api\model\v1\Activity::detail($activityId);
        $promoterId = $this->reqParams['promoter_id'];//推广人ID
        $shareId = $this->reqParams['share_id'];//分享用户ID

        //判断当前用户是否已查看过活动
        $readLog = UserReadLog::where(['activity_id'=>$activityId,'user_id'=>$this->user->id])->find();
        if(!$readLog){
            UserReadLog::create([
                'activity_id'=>$activityId,
                'user_id'=>$this->user->id
            ]);

            //更新活动阅读数，分享数
            $activity->readnums+=1;
            if($shareId){
                $activity->sharenums+=1;
            }
            $activity->allowField(true)->save();
        }

        //更新推广人阅读数，被分享数
        if($promoterId && $shareId && ($promoterId!=$this->user->id)){
            //推广记录
            $activityShare = ActivityShare::
            where(['activity_id'=>$activityId,"promoter_id"=>$promoterId])
                ->find();

            //用户查看推广人分享的活动记录
            $readShareLog = UserReadShareLog::
            where(['activity_id'=>$activityId,"promoter_id"=>$promoterId
            ,'user_id'=>$this->user->id])
                ->find();

            if(!$readShareLog){
                UserReadShareLog::create([
                    "activity_id" => $activityId,
                    "promoter_id"=>$promoterId,
                    'user_id'=>$this->user->id
                ]);
                if(!$activityShare){
                    $activityShare = new ActivityShare();
                    $activityShare->activity_id = $activityId;
                    $activityShare->promoter_id = $promoterId;
                    $activityShare->readnums = 1;
                    if($promoterId!=$shareId){
                        $activityShare->sharenums = 1;
                    }
                }else{
                    $activityShare->readnums += 1;
                    if($promoterId!=$shareId){
                        $activityShare->sharenums += 1;
                    }
                }

                $activityShare->save();

            }
        }

        //推荐活动
        $where['id'] = ['neq',$activityId];
        $where['statusswitch'] = 1;
        $where['starttime'] = ['elt',time()];
        $where['endtime'] = ['gt',time()];
        $tuijian = \app\api\model\v1\Activity::with(['activity_sign'=>['user']])
            ->where($where)
            ->field("id,name,price,trueprice,mainimage,starttime,endtime")
            ->orderRaw('rand()')
            ->limit(1)
            ->find();
        if($tuijian){
            if($tuijian['endtime']>time()){//进行中
                $tuijian['status'] = "ing";
            }else if($tuijian['endtime']<=time()){//已结束
                $tuijian['status'] = "finish";
            }
        }

        $this->success("活动详情",['info'=>$activity,'tuijian'=>$tuijian,'showgzh'=>0]);
    }

    public function getmincode(){
        $activityId = $this->reqParams['activity_id'];
        $promoterId = $this->reqParams['promoter_id']?:0;

        $activity = \app\api\model\v1\Activity::detail($activityId);
        $scene = "sp=".$activityId.".".$this->user->id.".".$promoterId.".0";
        $where['scene'] = $scene;
        $where['user_id'] = $this->user->id;
        $where['activity_id'] = $activityId;
        $mincode = Mincode::where($where)->find();
        if(is_file(".".$mincode->path)){
            $filepath = $mincode->path;
        }else{
            if($mincode){
                $mincode->delete();
            }
            $lineColor = [
                "r" => "0",
                "g" => "0",
                "b" => "0",
            ];
            $imginfo = getMincode($this->reqParams['xcxappid'],$this->reqParams['xcxsecret'],$scene,'develop',$lineColor,true);
            if(strlen($imginfo)<500){
                $this->error("小程序码生成失败，请重试");
            }
            $filename = date("YmdHis").rand(1000,9999).$activityId.$this->user->id.".jpg";
            $path = "uploads/mincode/".$filename;
            $filepath = "/".$path;

            file_put_contents($path,$imginfo);
            Attachment::saveFile($filename,$filepath,3);

            Mincode::create([
                "user_id" => $this->user->id,
                "activity_id" => $activityId,
                "scene" => $scene,
                "path" => $filepath,
            ]);
        }
        $this->success("小程序码",['mincode'=>fiximgurl($filepath),"shareurl"=>$scene]);
    }
    public function signup(){
        $promoterId = $this->reqParams['promoter_id'];
        $activityId = $this->reqParams['activity_id'];
        if(!$activityId){
            $this->error("活动不存在");
        }
        $activity = \app\api\model\v1\Activity::where(['id'=>$this->reqParams['activity_id'],"statusswitch"=>1])->find();
        \app\api\model\v1\Activity::verifyActivity($activity);
        if($activity->manlimit!=0 && $activity->signnums>=$activity->manlimit){
            $this->error("活动名额已满，请查看其他活动");
        }
        $has = \app\api\model\v1\Activity::issign($activityId,$this->user->id);
        if($has){
            $this->error("您已经报名过了!");
        }
        $info = $this->reqParams['info'];

        if(!$info){
            $this->error();
        }
        $info = array_column($info,null,"id");
        $forms = ActivityForm::where(['id'=>['in',$activity->activity_form_ids]])->select();
        if($forms){
            $data = [
                "user_id" => $this->user->id,
                "activity_id" => $activityId,
                "store_id" => $activity->store_id,
                "promoter_id" => $promoterId?:0,
            ];
            $infodata = [];

            foreach ($forms as $k => $v){
                $ifn = $info[$v['id']];
                $arr = [];
                if($v['isrequired']==1 && !$ifn['value']){
                    $this->error("请填写".$v['title']);
                }
                if($v['title']=='手机号' && !is_mobile($ifn['value'])){
                    $this->error("手机号有误");
                }
                if($v['type'] == 3 || $v['type']==4){//上传文件或图片 检测图片地址
                    $files = explode(",",$ifn['value']);
                    foreach ($files as $vv){
                        if(!is_file(".".str_replace(config("img_domain"),"",$vv))){
                            $this->error("上传的文件有误");
                        }
                    }
                }
                $arr = [
                    "formid" => $v['id'],
                    "title" => $v['title'],
                    "type" => $v['type'],
                    "value" => $ifn['value']?:"",
                ];
                array_push($infodata,$arr);
            }
            $data['info'] = json_encode($infodata);
            Db::startTrans();
            $result1 = ActivitySign::create($data);
            //更新活动报名数
            $activity->signnums+=1;
            $result2 = $activity->save();
            $result3 = true;
            //更新推广人报名数
            if($promoterId){
                $activityShare = ActivityShare::where(['activity_id'=>$activityId,"promoter_id"=>$promoterId])->find();
                if($activityShare){
                    $activityShare->signnums+=1;
                    $result3 = $activityShare->save();
                }
            }
            if($result1 && $result2 && $result3){
                Db::commit();
                $this->success("报名成功",intval($result1->id));
            }else{
                Db::rollback();
                $this->error("报名失败，请重试");
            }
        }else{
            $this->error("报名表单不存在");
        }

    }

    public function issign(){
        $this->success("报名状态",['status'=>\app\api\model\v1\Activity::issign($this->reqParams['activity_id'],$this->user->id)]);
    }
    public function signinfo(){
        $where['user_id'] = $this->user->id;
        $where['id'] = $this->reqParams['sign_id'];
        $info = ActivitySign::where($where)->find();
        if(!$info){
            $this->error("报名信息不存在");
        }
        $signinfo = json_decode($info->info,true);
        $activityFormIds = array_column($signinfo,"formid");
        $activityFormIdsInfo = array_column($signinfo,null,"formid");
        $forms = ActivityForm::where(['id'=>['in',$activityFormIds]])
            ->field("id,title,isrequired,type,options")->select();
        if($forms){
            foreach ($forms as $k => $v){
                $forms[$k]['activity_id'] = $info->activity_id;
                $forms[$k]['options'] = $v['options']?explode(",",$v['options']):[];
                $forms[$k]['value'] = $activityFormIdsInfo[$v->id]['value'];
            }
        }
        $this->success("报名信息",$forms);

    }
    public function editsign()
    {
        $signId = intval($this->reqParams['sign_id']);
        $activitySign = ActivitySign::with('activity')->where(['id' => $signId, 'user_id' => $this->user->id])->find();
        if (!$activitySign) {
            $this->error("报名信息不存在");
        }
        $activity = $activitySign->activity;
        \app\api\model\v1\Activity::verifyActivity($activity);
        $info = $this->reqParams['info'];
        if (!$info) {
            $this->error();
        }
        $info = array_column($info,null,"id");
        $forms = ActivityForm::where(['id'=>['in',$activity->activity_form_ids]])->select();
        if($forms){
            $infodata = [];
            foreach ($forms as $k => $v){
                $ifn = $info[$v['id']];
                $arr = [];
                if($v['isrequired']==1 && !$ifn['value']){
                    $this->error("请填写".$v['title']);
                }
                if($v['type'] == 3 || $v['type']==4){//上传文件或图片 检测图片地址
                    $files = explode(",",$ifn['value']);
                    foreach ($files as $vv){
                        if(!is_file(".".$vv)){
                            $this->error("上传的文件有误");
                        }
                    }
                }
                $arr = [
                    "formid" => $v['id'],
                    "title" => $v['title'],
                    "type" => $v['type'],
                    "value" => $ifn['value']?:"",
                ];
                array_push($infodata,$arr);
            }
            $activitySign->info = json_encode($infodata);
            $activitySign->updatetime = time();
            $result = $activitySign->save();
            if($result){
                $this->success("修改成功",$signId);
            }else{
                $this->error("修改失败");
            }
        }else{
            $this->error("报名表单不存在");
        }

    }

}
